package com.lfy.kcat.content.biz.impl;

import com.lfy.kcat.content.biz.DramaPublishService;
import com.lfy.kcat.content.domain.*;
import com.lfy.kcat.content.domain.bo.DramasBo;
import com.lfy.kcat.content.domain.bo.EpisodesBo;
import com.lfy.kcat.content.domain.vo.DramaPublishVo;
import com.lfy.kcat.content.domain.vo.DramasVo;
//import com.lfy.kcat.content.domain.vo.PublishActorsVo;
import com.lfy.kcat.content.domain.vo.PublishActorsVo;
import com.lfy.kcat.content.feign.CamundaFeignClient;
import com.lfy.kcat.content.mapper.ActorsMapper;
import com.lfy.kcat.content.mapper.DramasMapper;
import com.lfy.kcat.content.service.*;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.dto.DramaAuthStartDTO;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author leifengyang
 * @version 1.0
 * @date 2025/9/5 15:33
 * @description:
 */
@Slf4j
@Service
public class DramaPublishServiceImpl implements DramaPublishService {


    @Autowired
    DramasMapper  dramaMapper;

    @Autowired
    DramaCategoriesService dramaCategoriesService;

    @Autowired
    DramaTagsService dramaTagsService;

    @Autowired
    DramaActorsService dramaActorsService;

    @Autowired
    ActorsMapper actorsMapper;

    @Autowired
    IEpisodesService episodesService;

    @Autowired
    DramaAuthService dramaAuthService;



    /**
     * 单表多个操作，和多表操作都应该加事务；
     * @param dramaPublishVo
     * @return
     */
    @Transactional
    @Override
    public Long publishDrama(DramaPublishVo dramaPublishVo) {
        //1、从Vo中解出短剧数据，保存数据库，生成短剧id
        Dramas dramas = buildDramaEntity(dramaPublishVo);
        //数据库保存完数据，MyBatisPlus
        dramaMapper.insert(dramas);
        //从Bean中直接获取刚才的自增id
        Long dramaId = dramas.getDramaId();
        log.info("dramaId:{}",dramaId);

        // ========= 以下所有的保存，都需要给数据库保存短剧id =======

        //2、保存短剧和分类的关联关系
        List<DramaCategories> list = buildDramaCategoryEntity(dramaPublishVo, dramaId);
        dramaCategoriesService.saveBatch(list);
        log.info("分类保存完成: {}",list);


        //3、保存短剧和标签的关联关系
        List<DramaTags> dramaTagsEntitys = buildDramaTagEntity(dramaPublishVo, dramaId);
        dramaTagsService.saveBatch(dramaTagsEntitys);
        log.info("标签保存完成: {}",dramaTagsEntitys);

        //4、保存演员数据
        List<PublishActorsVo> actors = dramaPublishVo.getActors();
        for (PublishActorsVo actor : actors) {
            //1: 数据库已经有的演员，只需要保存关联关系
            if (actor.getActorId()!=null && actor.getActorId()>0){
                //构建关联关系实体类
                DramaActors dramaActors = new DramaActors();
                dramaActors.setDramaId(dramaId);
                dramaActors.setActorId(actor.getActorId());
                dramaActors.setRoleName(actor.getRoleName());
                dramaActors.setRoleType(actor.getRoleType());
                dramaActors.setSortOrder(0);
                dramaActors.setCreateTime(new Date());
                dramaActorsService.save(dramaActors);
                log.info("老演员与短剧关系保存成功：{}",dramaActors);
            }else {
                //2: 数据库没有的演员，需要先保存演员，再保存关联关系
                //先保存演员
                Actors actorsEntity = buildActorEntity(actor);
                //保存演员
                actorsMapper.insert(actorsEntity);
                log.info("录入短剧时保存新演员成功：{}",actorsEntity);

                //构建演员和短剧的关系
                DramaActors dramaActors = new DramaActors();
                dramaActors.setDramaId(dramaId);
                dramaActors.setActorId(actorsEntity.getActorId());
                dramaActors.setRoleName(actor.getRoleName());
                dramaActors.setRoleType(actor.getRoleType());
                dramaActors.setCreateTime(new Date());
                dramaActorsService.save(dramaActors);
                log.info("新演员与短剧关系保存成功：{}",dramaActors);

            }
        }



        //5、保存剧集； 需要填充关联的短剧id
        List<EpisodesBo> episodes = dramaPublishVo.getEpisodes();
        for (EpisodesBo episode : episodes) {
            //每集设置短剧id
            episode.setDramaId(dramaId);
            //保存到数据库
            episodesService.insertByBo(episode);
        }


        //启动审核流程
        DramaAuthStartDTO startDTO = new DramaAuthStartDTO();
        startDTO.setDramaId(dramaId);
        startDTO.setDramaName(dramas.getTitle());
        startDTO.setDescription(dramas.getDescription());

        String processId = startDramaAuthProcess(startDTO);

        //TODO 保存短剧审核流程
        DramaAuth dramaAuth = new DramaAuth();
        dramaAuth.setDramaId(dramaId);
        dramaAuth.setProcessId(processId);
        dramaAuth.setStepName("");
        dramaAuth.setAuthStatus(0);

        dramaAuthService.save(dramaAuth);

        return dramaId;
    }


    @Autowired
    CamundaFeignClient camundaFeignClient;


    /**
     *
     * @param dramaAuthStartDTO
     * @return 返回审核流程id
     */
    @Override
    public String startDramaAuthProcess(DramaAuthStartDTO dramaAuthStartDTO) {
        //TODO 远程调用
        R r = camundaFeignClient.startDramaAuthProcess(dramaAuthStartDTO);
        return r.getData().toString();
    }

    @NotNull
    private static Actors buildActorEntity(PublishActorsVo actor) {
        Actors actorsEntity = new Actors();
        actorsEntity.setActorName(actor.getActorName());
        actorsEntity.setActorImg("");
        actorsEntity.setActorInfo("");
        actorsEntity.setHeight(0L);
        actorsEntity.setWeight(0L);
        actorsEntity.setConstellation("");
        actorsEntity.setNationality("");
        actorsEntity.setDramaCount(0L);
        actorsEntity.setFansCount(0L);
        actorsEntity.setIsHot(0L);
        actorsEntity.setStatus(0L);
        actorsEntity.setBirthday(new Date());
        return actorsEntity;
    }


    @NotNull
    private static List<DramaTags> buildDramaTagEntity(@NotNull DramaPublishVo dramaPublishVo, Long dramaId) {
        List<Long> tags = dramaPublishVo.getTags();
//        for (Long tag : tags) {
//            DramaTags dramaTags = new DramaTags();
//            //回填
//            dramaTags.setDramaId(dramaId);
//            dramaTags.setTagId(tag);
//            dramaTags.setCreateTime(new Date());
//
//        }
        List<DramaTags> dramaTagsEntitys = tags.stream().map(tagId -> {
            DramaTags dramaTags = new DramaTags();
            dramaTags.setDramaId(dramaId);
            dramaTags.setTagId(tagId);
            dramaTags.setCreateBy(0L);
            dramaTags.setUpdateBy(0L);
            dramaTags.setCreateDept(0L);
            dramaTags.setCreateTime(new Date());
            return dramaTags;
        }).toList();
        return dramaTagsEntitys;
    }

    @NotNull
    private static List<DramaCategories> buildDramaCategoryEntity(DramaPublishVo dramaPublishVo, Long dramaId) {
        List<Long> categories = dramaPublishVo.getCategories();
        //处理所有的分类id，变为数据库能存的记录
        List<DramaCategories> list = categories.stream()
            .map(val -> {
                DramaCategories dramaCategories = new DramaCategories();
                dramaCategories.setDramaId(dramaId);
                dramaCategories.setCategoryId(val);
                dramaCategories.setIsPrimary(0);
                dramaCategories.setCreateTime(new Date());
                return dramaCategories;
            }).toList();
        return list;
    }

    private static Dramas buildDramaEntity(DramaPublishVo dramaPublishVo) {
        DramasBo dramaVo = dramaPublishVo.getDrama();
        //这个 entity 的所有数据都要进库
        Dramas dramaEntity = new Dramas();
        //快捷操作：属性对拷; 直接保存，无需再填充一些其他值
        BeanUtils.copyProperties(dramaVo,dramaEntity);
        //以下如果数据库没有默认值，我们还想要给数据库存，就自己指定默认值
        dramaEntity.setFollowCount(0L);
        dramaEntity.setLikeCount(0L);
        dramaEntity.setPlayCount(0L);
        dramaEntity.setCreateTime(new Date());
        dramaEntity.setUpdateTime(new Date());

        return dramaEntity;
    }
}
